"""
API blueprint views for the Flask Blueprints demo.
"""
from flask import jsonify, render_template
from . import api


# Sample data for demonstration
users_data = [
    {'id': 1, 'username': 'alice', 'email': 'alice@example.com', 'created_at': '2023-01-01T12:00:00Z'},
    {'id': 2, 'username': 'bob', 'email': 'bob@example.com', 'created_at': '2023-01-02T12:00:00Z'},
    {'id': 3, 'username': 'charlie', 'email': 'charlie@example.com', 'created_at': '2023-01-03T12:00:00Z'}
]

posts_data = [
    {
        'id': 1,
        'title': 'Introduction to Flask Blueprints',
        'excerpt': 'Learn how to organize your Flask application using blueprints...',
        'author': {'id': 1, 'username': 'alice'},
        'created_at': '2023-01-01T13:00:00Z'
    },
    {
        'id': 2,
        'title': 'Building RESTful APIs with Flask',
        'excerpt': 'A guide to creating RESTful web services using Flask...',
        'author': {'id': 2, 'username': 'bob'},
        'created_at': '2023-01-02T13:00:00Z'
    },
    {
        'id': 3,
        'title': 'Advanced Flask Patterns',
        'excerpt': 'Explore advanced design patterns for Flask applications...',
        'author': {'id': 1, 'username': 'alice'},
        'created_at': '2023-01-03T13:00:00Z'
    }
]


@api.route('/')
def index():
    """API root endpoint."""
    return jsonify({
        'message': 'Welcome to the Flask Blueprints Demo API',
        'version': '1.0',
        'endpoints': {
            'users': '/api/users',
            'posts': '/api/posts',
            'docs': '/api/docs'
        }
    })


@api.route('/users')
def users():
    """Get all users."""
    return jsonify({'users': users_data})


@api.route('/users/<int:user_id>')
def user(user_id):
    """Get a specific user."""
    # Find the user with the given ID
    user = next((u for u in users_data if u['id'] == user_id), None)
    
    if user is None:
        return jsonify({'error': 'User not found'}), 404
    
    # Add posts by this user
    user_posts = [p for p in posts_data if p['author']['id'] == user_id]
    user['posts'] = user_posts
    
    return jsonify(user)


@api.route('/posts')
def posts():
    """Get all posts with pagination."""
    # In a real app, you would handle pagination parameters
    page = 1
    per_page = 10
    total = len(posts_data)
    pages = (total + per_page - 1) // per_page
    
    return jsonify({
        'posts': posts_data,
        'pagination': {
            'page': page,
            'pages': pages,
            'per_page': per_page,
            'total': total
        }
    })


@api.route('/docs')
def docs():
    """API documentation."""
    return render_template('api/docs.html')